import React from 'react';
import moment from 'moment';
import { Picker, Flex, WhiteSpace } from 'antd-mobile';

import { yearAndMonth, getMonthWeekDays, getDays } from './util';

import './index.sass';

/**
 * defaultValue 默认年月值 [number,number]
 * onPanelChange //面板（年月）变化调用方法
 * onClick  //日期变化调用方法
 * dateCellRender 自定义渲染日期单元格，返回内容会被追加到单元格 function(date: moment): ReactNode
 * dateFullCellRender  自定义渲染日期单元格，返回内容覆盖单元格 function(date: moment): ReactNode
 * disabledDate  //不可选择的日期(currentDate: moment) => boolean
 * validRange  设置起始年份 [number, number]
 */

class Calendar extends React.Component {
  constructor(props) {
    super(props);
    const ym = yearAndMonth(this.props.validRange);
    const day =
      props.defaultValue || (ym.validRange[1] < Number(moment().format('YYYY')) && !ym.error)
        ? moment(`${ym.validRange[0]}-${moment().format('MM')}-${moment().format('DD')}`, 'YYYY-MM-DD')
        : moment();
    const obj = getMonthWeekDays(day);
    const days = getDays(obj.week, obj.days);
    this.state = {
      today: moment(),
      day,
      value: [Number(day.format('YYYY')), Number(day.format('MM'))],
      obj,
      days,
      valueDay: Number(day.format('DD')),
      yearAndMonth: ym.yearAndMonth
    };
  }
  dayOnClick(day) {
    // console.log(this.state.value,day);
    this.setState(
      {
        valueDay: Number(day)
      },
      () => {
        // console.log(moment(`${this.state.value[0]}-${this.state.value[1]}-${day}`, 'YYYY-M-D').format('YYYY-MM-DD'))
        if (this.props.onClick) {
          const { value } = this.state;
          this.props.onClick(moment(`${value[0]}-${value[1]}-${day}`, 'YYYY-M-DD'));
        }
      }
    );
  }

  changeMonth(type) {
    const { value } = this.state;
    const month = Number(value[1]);
    const year = Number(value[0]);
    if (type === 'pre') {
      if (month === 1) {
        this.setState(
          {
            value: [year - 1, 12]
          },
          () => {
            this.onYearOrMonthChange();
          }
        );
      } else {
        this.setState(
          {
            value: [year, month - 1]
          },
          () => {
            this.onYearOrMonthChange();
          }
        );
      }
    } else if (type === 'next') {
      if (month === 12) {
        this.setState(
          {
            value: [year + 1, 1]
          },
          () => {
            this.onYearOrMonthChange();
          }
        );
      } else {
        this.setState(
          {
            value: [year, month + 1]
          },
          () => {
            this.onYearOrMonthChange();
          }
        );
      }
    } else {
    }
  }

  onYearOrMonthChange() {
    const { value, valueDay } = this.state;
    const date = moment(`${value[0]}-${value[1]}-${valueDay}`, 'YYYY-M-D');
    const obj = getMonthWeekDays(date);
    const days = getDays(obj.week, obj.days);
    this.setState({ days }, () => {
      this.props.onPanelChange && this.props.onPanelChange(date);
    });
  }

  renderDay(children) {
    const {
      valueDay, day, value, today
    } = this.state;
    const { disabledDate, dateFullCellRender } = this.props;
    const currentDate = moment(`${value[0]}-${value[1]}-${children}`, 'YYYY-M-D');
    const isToday = today.format('YYYY-MM-DD') === currentDate.format('YYYY-MM-DD');
    const disabled = disabledDate ? disabledDate(currentDate) : false;
    return (
      <div className="l-calendar-content-day-container">
        {dateFullCellRender && dateFullCellRender(currentDate)}
        {!dateFullCellRender && (
          <span
            className={
              disabled
                ? `l-calendar-content-day ${
                  isToday ? 'l-calendar-content-day-today ' : ''
                }l-calendar-content-day-disabled${
                  Number(valueDay) === Number(children) ? ' l-calendar-content-day-checked' : ''
                }`
                : `${isToday ? 'l-calendar-content-day-today ' : ''}l-calendar-content-day${
                  Number(valueDay) === Number(children) ? ' l-calendar-content-day-checked' : ''
                }`
            }
            onClick={() => {
              !disabled && this.dayOnClick(children);
            }}
          >
            {children}
          </span>
        )}
        {!dateFullCellRender && this.props.dateCellRender && this.props.dateCellRender(currentDate)}
      </div>
    );
  }
  renderDays(days) {
    const hh = [];
    for (let i = 0, len = days.length; i < len;) {
      hh.push(<WhiteSpace key={`${i}-WhiteSpace`} />);
      hh.push(<Flex key={i}>
        <Flex.Item>{this.renderDay(days[i])}</Flex.Item>
        <Flex.Item>{this.renderDay(days[i + 1])}</Flex.Item>
        <Flex.Item>{this.renderDay(days[i + 2])}</Flex.Item>
        <Flex.Item>{this.renderDay(days[i + 3])}</Flex.Item>
        <Flex.Item>{this.renderDay(days[i + 4])}</Flex.Item>
        <Flex.Item>{this.renderDay(days[i + 5])}</Flex.Item>
        <Flex.Item>{this.renderDay(days[i + 6])}</Flex.Item>
      </Flex>);
      i += 7;
    }
    return hh;
  }
  render() {
    const { value, days, yearAndMonth } = this.state;
    const rdays = this.renderDays(days);
    return (
      <div className="l-calendar-container">
        <div className="l-calendar-header">
          <span
            onClick={() => {
              this.changeMonth('pre');
            }}
            className="l-calendar-header-lt"
          >
            {' '}
            &lt;{' '}
          </span>
          <span style={{ display: 'inline-block' }}>
            <Picker
              data={yearAndMonth}
              title="选择年月"
              cascade={false}
              extra="请选择(可选)"
              value={this.state.value}
              onPanelChange={v => {
                this.setState({ value: v });
              }}
              onOk={v => {
                this.setState(
                  {
                    value: v
                  },
                  () => {
                    this.onYearOrMonthChange();
                  }
                );
              }}
            >
              <span>
                {value[0]} 年 {value[1]} 月
              </span>
            </Picker>
          </span>
          <span
            onClick={() => {
              this.changeMonth('next');
            }}
            className="l-calendar-header-gt"
          >
            {' '}
            &gt;{' '}
          </span>
        </div>
        <WhiteSpace />
        <div className="l-calendar-content">
          <Flex>
            <Flex.Item>日</Flex.Item>
            <Flex.Item>一</Flex.Item>
            <Flex.Item>二</Flex.Item>
            <Flex.Item>三</Flex.Item>
            <Flex.Item>四</Flex.Item>
            <Flex.Item>五</Flex.Item>
            <Flex.Item>六</Flex.Item>
          </Flex>
          {rdays}
        </div>
      </div>
    );
  }
}

export default Calendar;
